package com.onlyphoto.onlymall.mvp.view.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.Gravity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.bean.GoodsSimpleBean
import com.onlyphoto.onlymall.bean.OrderConfirmFooterBean
import com.onlyphoto.onlymall.bean.request.CartGoodsBean
import com.onlyphoto.onlymall.bean.request.CartShopBean
import com.onlyphoto.onlymall.bean.request.PayBean
import com.onlyphoto.onlymall.bean.response.AddressBean
import com.onlyphoto.onlymall.bean.response.CouponBean
import com.onlyphoto.onlymall.bean.response.FreightBean
import com.onlyphoto.onlymall.bean.response.OrderSuccessBean
import com.onlyphoto.onlymall.events.ShowCouponsEvent
import com.onlyphoto.onlymall.mvp.contract.COrderConfirm
import com.onlyphoto.onlymall.mvp.presenter.POrderConfirmImpl
import com.onlyphoto.onlymall.mvp.view.binder.*
import com.onlyphoto.onlymall.utils.SharePreferenceUtil
import com.onlyphoto.onlymall.utils.ToastUtil
import com.onlyphoto.onlymall.widget.CouponsPopupView
import kotlinx.android.synthetic.main.activity_orderconfirm.*

import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class OrderConfirmActivity : BaseActivity<POrderConfirmImpl>(), COrderConfirm.IVOrderConfirm {

    var adapter: MultiTypeAdapter? = null
    var items: Items? = null
    var layoutManager: LinearLayoutManager? = null
    var address = "添加收货地址"
    var list: ArrayList<CartGoodsBean>? = null
    private var fromDetails = false
    private var totalPrice = 0.00
    var freight = 0
    var popupView: CouponsPopupView? = null
    var addressId = 0
    var addressIndex = 0
    var presence = false
    var couponId = 0

    private var isAllowUploadImg = false

    companion object {
        const val REQUEST_ADDRESS = 100
    }

    override fun retry() {}

    override fun init() {
        list = intent.getSerializableExtra("goodsList") as ArrayList<CartGoodsBean>?
        fromDetails = intent.getBooleanExtra("fromDetails", false)

        isAllowUploadImg = list!![0].allow_user_img == 1

        items = Items()
        adapter = MultiTypeAdapter(items!!)
        adapter?.register(String::class.java, OrderConfirmHeaderBinder())
        adapter?.register(CartGoodsBean::class.java, OrderGoodsBinder())
        adapter?.register(OrderConfirmFooterBean::class.java, OrderConfirmFooterBinder())
        layoutManager = LinearLayoutManager(this)
        rv_order.layoutManager = layoutManager
        rv_order.adapter = adapter
        popupView = CouponsPopupView(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        //点击事件初始化
        popupView?.setFinishedListener{id, name, price->
            items?.removeAt(items?.size!! - 1)
            items?.add(OrderConfirmFooterBean(name, totalPrice, freight))
            adapter?.notifyDataSetChanged()
            amount.text = "¥ " + (totalPrice + freight - price)
            couponId = id
        }

        create_order.setOnClickListener{
            mPresenter?.createOrder()
        }

        back.setOnClickListener{
            finish()
        }
    }

    override fun getPayBean(): PayBean {
        val payBean = PayBean()
        payBean.user_address_id = addressId
        if (fromDetails) {
            payBean.post_type = 1
            payBean.buy_num = list?.get(0)?.buy_num!!
            payBean.goods_id = list?.get(0)?.goods_id!!
            payBean.style = list?.get(0)?.style!!
            payBean.color = list?.get(0)?.color!!
            payBean.size = list?.get(0)?.size!!
        } else {
            payBean.post_type = 2
            val shopList = ArrayList<CartShopBean>()
            for (bean in list!!){
                val cartShopBean = CartShopBean()
                cartShopBean.cart_id = bean.id
                cartShopBean.goods_id = bean.goods_id
                cartShopBean.buy_num = bean.buy_num
                cartShopBean.style = bean.style
                cartShopBean.color = bean.color
                cartShopBean.size = bean.size
                shopList.add(cartShopBean)
            }
            payBean.data_json = Gson().toJson(shopList)
        }
        payBean.voucherl_id = couponId
        return payBean
    }

    override fun showToast(msg: String) {
        ToastUtil.showToast(msg)
    }

    override fun loadData() {
        //加载数据
        items?.add(address)
        items?.addAll(list!!)
        items?.add(OrderConfirmFooterBean("", 0.00, 0))
        mPresenter?.getAddress()
        val paramList = ArrayList<GoodsSimpleBean>()
        for (bean in list!!) {
            totalPrice += bean.price * bean.buy_num
            val goodsSimpleBean = GoodsSimpleBean(bean.goods_id, bean.buy_num)
            paramList.add(goodsSimpleBean)
        }
        mPresenter?.getFreight(paramList)
        mPresenter?.getUserCoupons(2, 0)
    }

    override fun getAddressSuccess(list: ArrayList<AddressBean>) {
        if (addressId != 0){
            for ((index, AddressBean) in list.withIndex()) {
                if (AddressBean.id == addressId) {
                    presence = true
                    addressIndex = index
                }
            }
            if (!presence) {
                addressIndex = 0
            }
        }

        addressId = list[addressIndex].id
        address = list[addressIndex].name + "  " + list[addressIndex].phone + "\n" +
                list[addressIndex].province + list[addressIndex].city + list[addressIndex].district + list[addressIndex].place
        items?.removeAt(0)
        items?.add(0, address)
        adapter?.notifyDataSetChanged()
    }

    override fun emptyAddress() {
        items?.removeAt(0)
        items?.add(0, "添加收货地址")
        adapter?.notifyDataSetChanged()
    }

    @SuppressLint("SetTextI18n")
    override fun getFreightSuccess(bean: FreightBean) {
        freight = bean.total_freight
        items?.removeAt(items?.size!! - 1)
        items?.add(OrderConfirmFooterBean("", totalPrice, freight))
        adapter?.notifyDataSetChanged()
        amount.text = "¥ " + (totalPrice + freight)
    }

    override fun getCouponsSuccess(list: ArrayList<CouponBean>) {
        popupView?.setData(list)
    }

    override fun orderCreateSuccess(data: OrderSuccessBean) {
        startActivity(Intent(this, PayMethodActivity::class.java)
                .putExtra("orderId", data.order_id)
                .putExtra("payPrice", data.pay_price))
        if (isAllowUploadImg) {
            SharePreferenceUtil.getInstance(this).setIntData("reservedOrderId", data.order_id.toInt())
        }
        finish()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ShowCouponsEvent) {
        val window = this.window
        val lp = window.attributes
        lp.alpha = 0.38f
        window.attributes = lp
        popupView?.showAtLocation(ll_confirm, Gravity.BOTTOM, 0, 0)
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    override fun setContentViewId(): Int {
        return R.layout.activity_orderconfirm
    }

    override fun createPresenter() {
        mPresenter = POrderConfirmImpl(mContext, this)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    override fun onResume() {
        super.onResume()
        presence = false
        mPresenter?.getAddress()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            if (requestCode == REQUEST_ADDRESS) {
                val id  = data.getIntExtra("result", 0)
                addressId = id
                mPresenter?.getAddress()
            }
        }
    }
}
